package com.gy.controller.result;

import com.alibaba.excel.EasyExcel;
import com.gy.controller.common.UserHolder;
import com.gy.entity.Export.CustomCellWriteHandler;
import com.gy.entity.Export.ExportField;
import com.gy.entity.Export.ExportRequest;
import com.gy.entity.result.Patents;
import com.gy.query.PatentsQuery;
import com.gy.result.Result;
import com.gy.service.PatentsService;
import com.gy.vo.PageVO;
import com.gy.vo.summary.PatentsVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/patents")
@Api(tags = "专利接口")
@CrossOrigin
public class PatentsController {

    @Resource
    private PatentsService patentsService;

    /**
     * 根据openid分页查看某个人的专利信息
     */
    @PostMapping("/getPatents")
    @ApiOperation("根据openid查看某个人的专利信息")
    public Result<PageVO<Patents>> getPatents(@RequestBody PatentsQuery patentsQuery){
        return patentsService.getPatents(patentsQuery);
    }

    /**
     * 新增专利信息
     */
    @PostMapping("/save")
    @ApiOperation("新增专利")
    public Result AddPapers(@RequestBody Patents patents){
        Result result=patentsService.savePatent(patents);
        return result;
    }


    /**
     * 根据专利id主键删除专利
     */
    @DeleteMapping("/deleteById/{id}")
    @ApiOperation("根据专利id主键删除专利")
    public Result deleteById(@PathVariable Long id){
        return patentsService.removePatentById(id);
    }

    /**
     * 更改专利信息
     */
    @PutMapping("/update")
    @ApiOperation("更改专利信息")
    public Result update(@RequestBody Patents patents){
        return patentsService.updatePapers(patents);
    }


    /**
     * 根据专利id主键查看专利
     */
    @GetMapping("/getPatentsById/{id}")
    @ApiOperation("根据专利id主键查看专利")
    public Result getPatentsById(@PathVariable Long id){
        Patents serviceById = patentsService.getPatentsById(id);
        return Result.success(serviceById);
    }

    /**
     * 通过多个id查询论文信息
     */
    @PostMapping("/getPatentsByIds")
    @ApiOperation("通过多个id查询专利信息")
    public Result getPatentsByIds(@RequestBody Long[] ids){
        return patentsService.getPatentsByIds(ids);
    }
    /**
     * excel批量导出
     */
    @PostMapping("/export/patents")
    @ApiOperation("excel批量导出")
    public void exportPapers(@RequestBody ExportRequest request, HttpServletResponse response) throws IOException {
        List<ExportField> fields = request.getFields();
        List<Map<String, Object>> data = request.getData();

        String fileName = "exported_patents.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 动态生成表头
        List<List<String>> head = fields.stream()
                .map(field -> Arrays.asList(field.getLabel()))
                .collect(Collectors.toList());

        // 将 Map<String, Object> 转换为 List<List<Object>>
        List<List<Object>> transformedData = data.stream()
                .map(map -> fields.stream()
                        .map(field -> map.get(field.getKey()))
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());

        // 写入数据
        EasyExcel.write(response.getOutputStream())
                .head(head)
                .registerWriteHandler(new CustomCellWriteHandler(fields))
                .sheet("Patents")
                .doWrite(transformedData);
    }


    /**
     * 汇总表格中返回专利信息
     */
    @GetMapping("/getPatentsBySummary")
    @ApiOperation("汇总表格中返回专利信息")
    public Result<List<PatentsVO>> getPatentsBySummary() {
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("用户登录信息异常");
        }

        // 查询并选择 PatentsVo 中的字段
        List<Patents> list = patentsService.lambdaQuery()
                .eq(Patents::getUserId, userId)
                .select(
                        Patents::getId,
                        Patents::getTitle,
                        Patents::getPatentType,
                        Patents::getPatentNumber,
                        Patents::getAuthorizationDate,
                        Patents::getApplicationDate,
                        Patents::getAuthorRank,
                        Patents::getApplicationNumber,
                        Patents::getPatentStatus,
                        Patents::getPatentOwner
                )
                .list();

        // 将查询结果转换为 PatentsVo 列表
        List<PatentsVO> voList = list.stream()
                .map(patent -> PatentsVO.builder()
                        .title(patent.getTitle())
                        .patentType(patent.getPatentType())
                        .patentNumber(patent.getPatentNumber())
                        .authorizationDate(patent.getAuthorizationDate())
                        .applicationDate(patent.getApplicationDate())
                        .authorRank(patent.getAuthorRank())
                        .applicationNumber(patent.getApplicationNumber())
                        .patentStatus(patent.getPatentStatus())
                        .patentOwner(patent.getPatentOwner())
                        .build())
                .collect(Collectors.toList());

        return Result.success(voList);
    }

}
